
package com.pp.admin.common.server.service;

import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.Cookie;

import com.google.appengine.api.datastore.Key;
import com.pp.admin.common.client.beans.LoginUserInfo;
import com.pp.admin.common.client.exceptions.DomainAuthException;
import com.pp.admin.common.client.exceptions.InvalidUserException;
import com.pp.admin.common.client.exceptions.UserIsNotLogedIn;
import com.pp.admin.common.client.service.LoginService;
import com.pp.admin.common.server.PersistenceManagerFactory;
import com.pp.admin.common.server.entities.Domain;
import com.pp.admin.common.server.entities.User;
import com.pp.admin.common.server.entities.UsersDomain;

public class LoginServiceImpl extends BaseAdminService implements LoginService {
	
	/**
	 * 
	 */
	private static final long	serialVersionUID	= 6073004674105359879L;
	
	private static final Logger	LOG					= Logger.getLogger( LoginServiceImpl.class.getName() );
	
	@Override
	public LoginUserInfo isUserLogedIn( String domainID ) throws DomainAuthException, UserIsNotLogedIn {

		LoginUserInfo currentUser = null;
		try {
			Cookie userCookie = getCookie( USERID_COOKIE );
			
			if ( userCookie != null ) {
				User user = User.getUserByUserID( userCookie.getValue() );
				
				currentUser = user.exportLoginUserInfo( domainID );
			}
		} catch ( Exception ex ) {
			currentUser = null;
			throw new UserIsNotLogedIn();
		}
		return currentUser;
	}
	
	@Override
	public void logOut() {

		Cookie cuurentDomainCookie = new Cookie( USERID_COOKIE, null );
		cuurentDomainCookie.setPath( "/" );
		this.getThreadLocalResponse().addCookie( cuurentDomainCookie );
	}
	
	@SuppressWarnings( "unchecked" )
	@Override
	public void createUser( String HostURL ) {

		PersistenceManager pm = PersistenceManagerFactory.getPersistenceManager();
		try {
			//			Query query = pm.newQuery( User.class );
			//			List<User> userresults = (List<User>) query.execute();
			//			for ( User user : userresults ) {
			//				// pm.deletePersistent(user);
			//				System.out.println( "user => " + user.getId().toString() );
			//			}
			//			query = pm.newQuery( UsersDomain.class );
			//			List<UsersDomain> results = (List<UsersDomain>) query.execute();
			//			for ( UsersDomain usersDomain : results ) {
			//				System.out.println( "userDomain => " + usersDomain.getId().toString() );
			//				LOG.config( "userDomain => " + usersDomain );
			//			}
			//			query = pm.newQuery( Domain.class );
			//			List<Domain> domainresults = (List<Domain>) query.execute();
			//			for ( Domain domain : domainresults ) {
			//				System.out.println( "domain =>" + domain );
			//				LOG.config( "domain =>" + domain );
			//				List<UsersDomain> userdomains = domain.getUsersDomains();
			//				for ( UsersDomain usersDomain : userdomains ) {
			//					System.out.println( "userDomain under domain => " + usersDomain.getId().toString() );
			//					LOG.config( "userDomain under domain => " + usersDomain );
			//				}
			//			}
			
			String userID = "administrator";
			Key userKey = User.generateKey( userID );
			User user = new User();
			user.setUserID( "administrator" );
			user.setFirstName( "Administrator" );
			user.setPassword( "root123" );
			user.setStatus( User.STATUS_ACTIVE );
			user.setId( userKey );
			String domainID = "PP-ADMIN";
			Key domainKey = Domain.generateKey( userID, domainID );
			Domain domain = new Domain();
			domain.setId( domainKey );
			domain.setDomainID( domainID );
			domain.setUesrFriendlyName( "Administration" );
			domain.setStatus( Domain.STATUS_ACTIVE );
			domain.setHomeURL( HostURL + "Administrator.html" );
			Key userDomainKey = UsersDomain.generateKey( domainID, userID );
			UsersDomain userDomain = new UsersDomain();
			userDomain.setId( userDomainKey );
			userDomain.setUserKey( user.getId() );
			userDomain.setStatus( UsersDomain.STATUS_ACTIVE );
			userDomain.setSuperUser( UsersDomain.BOOLEAN_TRUE );
			domain.getUsersDomains().add( userDomain );
			user.getOwnerOfDomains().add( domain );
			user.save( pm );
		} finally {
			PersistenceManagerFactory.closePersistenceManager();
		}
	}
	
	@Override
	public LoginUserInfo login( String userID, String password, String domain ) throws InvalidUserException, DomainAuthException {

		LoginUserInfo userbean = null;
		try {
			User user = User.getUserByUserID( userID );
			
			if ( user == null ) {
				throw new InvalidUserException();
			} else if ( user.getPassword().equals( password ) ) {
				if ( user.getStatus() != User.STATUS_ACTIVE ) {
					throw new InvalidUserException();
				}
				userbean = user.exportLoginUserInfo( domain );
				setUserCookie( user );
			} else {
				throw new InvalidUserException();
			}
		} catch ( InvalidUserException e ) {
			throw e;
		} catch ( DomainAuthException ex ) {
			throw ex;
		} catch ( Exception ex ) {
			throw new InvalidUserException();
		}
		return userbean;
	}
	
	private void setUserCookie( User user ) {

		Cookie cuurentDomainCookie = new Cookie( USERID_COOKIE, user.getUserID() );
		cuurentDomainCookie.setPath( "/" );
		this.getThreadLocalResponse().addCookie( cuurentDomainCookie );
	}
}
